package com.firesoon;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
//import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

/**
 * @author yakun.zeng
 * @version 1.0
 * @description: TODO
 * @date 2025/7/28 19:21
 */
public class ControllerTimerAgent {

    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("ControllerTimerAgent started");

        new AgentBuilder.Default()
                .type(ElementMatchers.isAnnotatedWith(RestController.class)
//                        .or(ElementMatchers.isAnnotatedWith(Controller.class))
                )
                .transform(new AgentBuilder.Transformer() {
                    @Override
                    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, ProtectionDomain protectionDomain) {
                        return builder.method(ElementMatchers.isAnnotatedWith(RequestMapping.class)
                                        .or(ElementMatchers.isAnnotatedWith(GetMapping.class))
                                        .or(ElementMatchers.isAnnotatedWith(PostMapping.class))
                                        .or(ElementMatchers.isAnnotatedWith(PutMapping.class))
                                        .or(ElementMatchers.isAnnotatedWith(DeleteMapping.class))
                                        .or(ElementMatchers.isAnnotatedWith(PatchMapping.class)))
                                .intercept(MethodDelegation.to(ControllerTimerInterceptor.class));
                    }
                })
                .installOn(inst);
    }
}
